const db=wx.cloud.database()
const directionsCollection=db.collection('pc_directions')
const app=getApp()
Page({
    async onLoad(options){
        let res=await directionsCollection.get()
        let directions=res.data.map(v=>{
            return v.name
        })
        if(app.globalData.user.choosen.length==0){
            app.globalData.user.choosen=directions.slice(0)
        }
        this.setData({
            directions,user:app.globalData.user
        })
    },
    change(e){
        //志愿选择的规则，编号靠前的志愿可随意选，后面只能选择前面没选过的
        console.log(e)
        let choosen=this.data.user.choosen
        let picked=this.data.directions[Number(e.detail.value)]
        //当前选择的志愿已经出现在前面的志愿中，就拒绝
        let found=choosen.indexOf(picked)
        if(found<e.currentTarget.dataset.id){
            wx.vibrateShort({
              type: 'light',
            })
            wx.showToast({
              title: `第${found+1}志愿已经选${picked}`,
              icon:'error'
            })
        }else{
            //将氮气志愿设置成选择的内容，把choosen对应成员替换
            choosen.splice(e.currentTarget.dataset.id,0,picked)
            choosen.splice(choosen.lastIndexOf(picked),1)
        }
        let user=this.data.user
        user.choosen=choosen
        this.setData({
            user
        })
    },
    async post(){
        let user=this.data.user
        let res=await wx.cloud.callFunction({
            name:'pc_post',
            data:{
                user
            }
        })
        if(res.result.res.errMsg.indexOf('ok')>0){
            wx.showToast({
              title: '提交成功',
            })
            wx.redirectTo({
              url: '/pages/work18/list',
            })
        }
    },
    data:{

    }
})